<template>
  <el-dialog 
    class="forward-dialog" 
    title="转发" 
    v-model="dialogVisible" 
    width="520px"
    :append-to-body="true"
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    @close="handleClose"
    center>
    <div class="forward-container">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="好友" name="friends">
          <el-input
            class="search-input"
            placeholder="搜索好友"
            v-model="searchText"
            prefix-icon="el-icon-search"
            clearable>
          </el-input>
          <div class="list-container" ref="friendList" @scroll="handleScroll">
            <el-checkbox-group v-model="selectedFriends">
              <div v-for="friend in displayFriends" :key="friend.id" class="list-item">
                <el-checkbox :label="friend.id">
                  <div class="item-content">
                    <head-image :url="friend.headImage" :name="friend.nickName" :size="40"></head-image>
                    <span class="name">{{ friend.nickName }}</span>
                  </div>
                </el-checkbox>
              </div>
            </el-checkbox-group>
            <div v-if="loading" class="loading-text">加载中...</div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="群聊" name="groups">
          <el-input
            class="search-input"
            placeholder="搜索群聊"
            v-model="searchText"
            prefix-icon="el-icon-search"
            clearable>
          </el-input>
          <div class="list-container" ref="groupList" @scroll="handleScroll">
            <el-checkbox-group v-model="selectedGroups">
              <div v-for="group in displayGroups" :key="group.id" class="list-item">
                <el-checkbox :label="group.id">
                  <div class="item-content">
                    <head-image :url="group.headImage" :name="group.name" :size="40"></head-image>
                    <span class="name">{{ group.name }}</span>
                  </div>
                </el-checkbox>
              </div>
            </el-checkbox-group>
            <div v-if="loading" class="loading-text">加载中...</div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleForward" :loading="forwarding">转发</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import HeadImage from '../common/HeadImage.vue'

export default {
  name: 'ForwardDialog',
  components: {
    HeadImage
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    message: {
      type: Object,
      required: true
    }
  },
  emits: ['update:modelValue', 'close'],
  data() {
    return {
      dialogVisible: false,
      activeTab: 'friends',
      searchText: '',
      selectedFriends: [],
      selectedGroups: [],
      forwarding: false,
      loading: false,
      pageSize: 20,
      displayFriends: [],
      displayGroups: [],
      currentPage: 1
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.modelValue;
      },
      set(val) {
        this.$emit('update:modelValue', val);
      }
    },
    friends() {
      return this.$store.state.friendStore.friends
    },
    groups() {
      return this.$store.state.groupStore.groups
    },
    filteredFriends() {
      return this.friends.filter(friend => 
        friend.nickName.toLowerCase().includes(this.searchText.toLowerCase())
      )
    },
    filteredGroups() {
      return this.groups.filter(group => 
        group.name.toLowerCase().includes(this.searchText.toLowerCase())
      )
    }
  },
  watch: {
    modelValue: {
      immediate: true,
      handler(val) {
        if (val) {
          this.initData();
          console.log('ForwardDialog - 对话框已打开，modelValue:', val);
        } else {
          this.resetSelection();
        }
      }
    }
  },
  methods: {
    initData() {
      this.currentPage = 1
      this.displayFriends = []
      this.displayGroups = []
      this.loadMoreData()
    },

    handleTabClick() {
      this.currentPage = 1
      this.displayFriends = []
      this.displayGroups = []
      this.loadMoreData()
    },

    handleScroll(e) {
      const target = e.target
      const scrollHeight = target.scrollHeight
      const scrollTop = target.scrollTop
      const clientHeight = target.clientHeight
      
      if (scrollHeight - scrollTop - clientHeight < 50 && !this.loading) {
        this.loadMoreData()
      }
    },

    loadMoreData() {
      if (this.loading) return
      
      this.loading = true
      const start = (this.currentPage - 1) * this.pageSize
      
      setTimeout(() => {
        if (this.activeTab === 'friends') {
          const newFriends = this.filteredFriends.slice(start, start + this.pageSize)
          this.displayFriends = [...this.displayFriends, ...newFriends]
        } else {
          const newGroups = this.filteredGroups.slice(start, start + this.pageSize)
          this.displayGroups = [...this.displayGroups, ...newGroups]
        }
        
        this.currentPage++
        this.loading = false
      }, 200)
    },

    handleClose() {
      this.dialogVisible = false;
      this.$emit('close');
    },

    async handleForward() {
      if (this.selectedFriends.length === 0 && this.selectedGroups.length === 0) {
        this.$message.warning('请选择转发对象')
        return
      }

      this.forwarding = true
      try {
        const targets = [
          ...this.selectedFriends.map(id => ({
            type: 'PRIVATE',
            targetId: id
          })),
          ...this.selectedGroups.map(id => ({
            type: 'GROUP',
            targetId: id
          }))
        ]

        for (const target of targets) {
          const chat = {
            type: target.type,
            targetId: target.targetId,
            showName: target.type === 'PRIVATE' ? 
              this.friends.find(f => f.id === target.targetId)?.nickName :
              this.groups.find(g => g.id === target.targetId)?.name,
            headImage: target.type === 'PRIVATE' ?
              this.friends.find(f => f.id === target.targetId)?.headImage :
              this.groups.find(g => g.id === target.targetId)?.headImage,
            unreadCount: 0,
            lastContent: '',
            lastTime: new Date().getTime(),
            messages: []
          }
          
          this.$store.commit('openChat', chat)

          const msgInfo = {
            type: this.message.type,
            content: this.message.content,
            chatType: target.type,
            sendTime: new Date().getTime(),
            selfSend: true,
            recvId: target.type === 'PRIVATE' ? target.targetId : undefined,
            groupId: target.type === 'GROUP' ? target.targetId : undefined
          }

          const res = await this.$http({
            url: `/message/${target.type.toLowerCase()}/send`,
            method: 'post',
            data: msgInfo
          })

          if (res) {
            res.selfSend = true
            this.$store.commit('insertMessage', res)
          }
        }

        this.$message.success(`已转发给${this.selectedFriends.length + this.selectedGroups.length}个会话`)
        this.handleClose()
      } catch (error) {
        console.error('转发失败:', error)
        this.$message.error('转发失败')
      } finally {
        this.forwarding = false
      }
    },

    resetSelection() {
      this.selectedFriends = []
      this.selectedGroups = []
      this.searchText = ''
      this.activeTab = 'friends'
      this.displayFriends = []
      this.displayGroups = []
      this.currentPage = 1
    }
  }
}
</script>

<style lang="scss">
.forward-dialog {
  .el-dialog__wrapper {
    overflow: hidden !important;
  }

  .el-dialog {
    margin: 0 !important;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .forward-container {
    padding: 0;
    
    .el-tabs__content {
      overflow: hidden;
    }
    
    .search-input {
      margin: 15px;
      
      .el-input__inner {
        border-radius: 4px;
      }
    }
    
    .list-container {
      height: 400px;
      overflow-y: auto;
      margin: 0 15px;
      
      .list-item {
        padding: 10px;
        border-bottom: 1px solid #eee;
        
        &:last-child {
          border-bottom: none;
        }
        
        .el-checkbox {
          width: 100%;
          margin-right: 0;
          
          .el-checkbox__label {
            width: 100%;
          }
        }
        
        .item-content {
          display: flex;
          align-items: center;
          
          .name {
            margin-left: 10px;
            font-size: 14px;
            color: #333;
          }
        }
      }
    }
  }

  .el-dialog {
    border-radius: 8px;
    
    .el-dialog__header {
      padding: 20px;
      background: #f8f9fa;
      margin: 0;
      border-bottom: 1px solid #eee;
      
      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
      }
    }
    
    .el-dialog__body {
      padding: 20px;
    }
    
    .el-dialog__footer {
      padding: 15px 20px;
      border-top: 1px solid #eee;
    }
  }
}

body.el-popup-parent--hidden {
  padding-right: 0 !important;
}

.list-container {
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: #ddd;
    border-radius: 3px;
  }
}
</style> 